import { defineStore } from "pinia"
import userInfoApi,{type LoginParamsData, type UserInfoData} from '@/api/userInfo'
import {allAsyncRoutes, staticRoutes,anyRoute} from '@/router/routes'
import type { RouteRecordRaw } from 'vue-router'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'

interface UserInfoStoreStateData {
    token:string,
    userInfo:UserInfoData,
    menuRoutes:RouteRecordRaw[]
}

// 从所有的菜单权限name中筛选出自己有的动态路由的name
function filterAsyncRoutes(allAsyncRoutes:RouteRecordRaw[],routeNames:string[]){
    let result = allAsyncRoutes.filter(item=>{
        if(routeNames.indexOf(item.name as string) !== -1){  //下标不等于-1的话证明存在
            if(item.children && item.children.length){
                item.children = filterAsyncRoutes(item.children,routeNames)
            }
            return true // 过滤结束
        }
    })
    return result   //将返回的数组数据return出去
}

// 将多个路由进行动态添加
function addRoutes(routes:RouteRecordRaw[]){
    routes.forEach(item=>{
        router.addRoute(item)
    })
}

// 退出登陆时需要将路由器中的路由删除掉  遍历删除
function removeRouters(){
    // 获取所有路由
    const allRouters = router.getRoutes()
    // 遍历删除路由
    allRouters.forEach(item=>{
        router.removeRoute(item.name as string)
    })
    // 重新注册静态路由
    addRoutes(staticRoutes)
}

export const useUserInfoStore = defineStore('userInfo',{
    // 数据
    state():UserInfoStoreStateData{  // 菠萝中存的token和用户信息
        return {
            token: localStorage.getItem('token_key') || '',
            userInfo:{
                name:'',
                avatar:'',
                routes:[], //菜单权限信息数据，一堆字符串,对应的是路由name值，需要根据这些字符串从所有的异步路由当中去过滤自己的异步路由
                buttons:[],
                roles:[]
            },
            menuRoutes:staticRoutes
        }
    },

    // 计算属性
    actions:{
        // 登录发送请求 获取到token给到菠萝中
        async login(loginParams:LoginParamsData){
            try {
              const result = await userInfoApi.userLogin(loginParams)
              this.token = result.token
              localStorage.setItem('token_key',result.token)
              return 'ok'
            } catch (error) {
              return Promise.reject(error)
            }
        },

        // 获取到用户信息
        async getUserInfo(){
            try {
              const result = await userInfoApi.getUserInfo()
              this.userInfo = result  // 用token获取到用户信息
              let userRoutes = filterAsyncRoutes(cloneDeep(allAsyncRoutes),result.routes)
              addRoutes(userRoutes.concat(anyRoute))
              this.menuRoutes = staticRoutes.concat(userRoutes,anyRoute)

              return 'ok'
            } catch (error) {
              return Promise.reject(error)
            }
        },

        // 清除token和清除 用户信息方法
        async reset(){
            this.token = '',
            this.userInfo = {
                name:'',
                avatar:'',
                routes:[],
                buttons:[],
                roles:[]
            }
            localStorage.removeItem('token_key')
        },

        //退出登录
        async logout(){
            try {
                await userInfoApi.userLogout()
                this.reset()  // 调用上面封装的方法
                removeRouters()
                return 'ok'
            } catch (error) {
                return Promise.reject('error')
            }
        }
    },

    getters:{

    }

})